var express = require('express');
var router = express.Router();
var query = require('../db');
var dayjs = require('dayjs');

/* GET home page. */
router.get('/', async function (req, res, next) {
  let sql = 'SELECT * FROM `user` ';
  let rows = await query(sql);
  console.log(rows);
  res.send('exam index');
});

router.post('/insert', async function (req, res, next) {
  let sql = 'SELECT e_name,  e_author FROM `exam` where `e_name`=? and `e_author`=?';
  let examData = req.body;
  let rows = await query(sql, [examData['e_name'], examData['e_author']]);
  // 时间戳最大数据为7fff ffff 即2038-01-19 11:14:07会溢出，所以输入时间不能高于这个数字
  let overTime = 2147483647;
  console.log('插入前查询是否有同名，返回:', rows);
  if (rows.length != 0) {
    return res.json({
      code: 20000,
      data: {
        message: `该场考试已存在！服务器查询到名为${rows[0].e_name}且作者为${rows[0].e_author}的考试`,
        type: 'warning',
      },
    });
  }
  if (overTime <= dayjs(req.body['begin_time']).unix()) {
    return res.json({
      code: 20000,
      data: {
        message: `警告! 您输入的时间溢出了，请不要输入超过${dayjs.unix(overTime).format('YYYY-MM-DD HH:mm:ss')}的时间！`,
        type: 'error',
      },
    });
  }
  sql =
    'INSERT INTO `exam`(`e_name`, `e_author`, `e_cid`, `e_pname`, `e_pauthor`, `begin_time`, `e_duration`, `DTXS`, `DLTM`, `BXHT`) VALUES (?,?,?,?,?,?,?,?,?,?)';

  rows = await query(sql, [
    examData['e_name'],
    examData['e_author'],
    examData['e_cid'],
    examData['e_pname'],
    examData['e_pauthor'],
    dayjs(req.body['begin_time']).format('YYYYMMDDHHmmss'), // Number(dayjs(req.body['begin_time']).unix()),//examData['begin_time'],
    examData['e_duration'],
    examData['DTXS'],
    examData['DLTM'],
    examData['BXHT'],
  ]);
  console.log('插入exam表：', rows);
  // console.log(dayjs(req.body['begin_time']).unix())
  return res.json({
    code: 20000,
    data: {
      message: `创建成功！`,
      type: 'success',
    },
  });
});

router.post('/select', async function (req, res, next) {
  let now = dayjs();
  let sql = 'SELECT * FROM `exam` where `e_author`=? ORDER BY `exam`.`begin_time` ASC';
  let examData = req.body;
  if(examData['e_author']===''){
    sql = 'SELECT * FROM `exam` ORDER BY `exam`.`begin_time` ASC';
  }
  let rows = await query(sql, [examData['e_author']]);
  let data = {
    serverTimeNow: now.format('YYYY年MM月DD日 HH:mm:ss'),
    haveBegunTableData: [], //正在进行中的考试
    isOverTableData: [], //已经结束的考试
    notStartTableData: [], //未开始的考试
  };
  // console.log(rows);
  for (let i = 0; i < rows.length; i++) {
    let beginTime = dayjs(rows[i]['begin_time']).unix();
    let endTime = dayjs(rows[i]['begin_time']).unix() + rows[i]['e_duration'] * 60; //e_duration是分钟，要乘以60转化为秒
    let nowTime = now.unix();
    if (nowTime < beginTime) {
      data.notStartTableData.push(rows[i]);

      // console.log(beginTime, ' ', endTime, ' ', nowTime, '插入未开始的');
    } else if (nowTime >= beginTime && nowTime <= endTime) {
      data.haveBegunTableData.push(rows[i]);
      // console.log(beginTime, ' ', endTime, ' ', nowTime, '插入进行中的');
    } else {
      data.isOverTableData.push(rows[i]);
      // console.log(beginTime, ' ', endTime, ' ', nowTime, '插入已经结束的');
    }
    rows[i]['begin_time'] = dayjs(rows[i]['begin_time']).format('YYYY年MM月DD日 HH:mm:ss');
  }
  // console.log(data);
  
  return res.json({
    code: 20000,
    data: data,
  });
});

router.post('/delete', async function (req, res, next) {
  let sql = 'DELETE FROM `exam` WHERE e_id = ? ';
  let examData = req.body;
  let rows = await query(sql, [examData['e_id']]);
  return res.json({
    code: 20000,
    data: {
      message: `删除成功！`,
      type: 'success',
    },
  });
});

module.exports = router;
